define(['jquery',
        'module/util',
        'jquery-weui',
        'jquery.pnotify', 
        'jquery.validate',
        'plugins'], 
function($, util){
	return {
		doMyAjax : function() {
			$.ajaxSetup({cache: false});
			$(document).ajaxError(function(event, xhr, settings, thrownError ) {
			    try{
				    var error = $.parseJSON(xhr.responseText);
				    if(error.code === 'SESSION_TIME_OUT'){
				    	$.toast("登陆已超时，请重新登陆", "cancel");
				    	setTimeout(function() {
				    		window.location.reload();
				    	}, 1000);
				    }else{
				    	$.toast(error.message, "cancel");
				    }
				}catch(Error){
					$.toast("资源加载失败，请刷新尝试", "cancel");					
				}
			});
			
			$(document).ajaxSuccess(function(event, xhr, settings) {
				try{
					// Status 206 (Partial Content) indicates that the partial HTML string
					// are returned as the ajax result, we need avoid to parseJSON against
					// the HTML string.
					if(xhr.status != 206){
						var result = $.parseJSON(xhr.responseText);
						if(result && result.hasOwnProperty('code') && result.hasOwnProperty('message') && result.hasOwnProperty('data')){
							if(result.code === 'ACK'){
								$.toast(result.message);
							} else if(result.code === 'NACK'){
								$.toast(result.message, "cancel");
							} else if(result.code === 'VALIDATION_ERROR'){
								$.toast(result.message, "cancel");
								$.each(result.data, function(i, obj){
									if(obj && obj.formId){
										var errors = {};
										if((obj.generalError || []).length !=0){
											$('#' + obj.formId).find('.general-error').show().text((obj.generalError || []).join(','));
										}
										if(obj.fieldErrors){
											$('#' + obj.formId).find('input,textarea').each(function(){
												var name = $(this).attr('data-prop') || $(this).attr('name');
												if(name && obj.fieldErrors.hasOwnProperty(name)){
													errors[name] = obj.fieldErrors[name];
												}
											});
											$('#' + obj.formId).validate().showErrors(errors);
										}
									}
								});
							} else if(result.code === 'REDIRECT'){
								if(result.message && result.message.length != 0) {
									$.toast(result.message);
								}
								util.redirect(result.data);
							}
						}
					}
				}catch(Error){
					$.toast("请求失败", "cancel");					
				}
			});
		}
	}
});